package util;

import javax.annotation.Resource;
import java.sql.*;

/**
 * @author Jason
 * @PACKAGE_NAME util
 * @Description 封装数据库连接
 * @date 2023-12-06 9:20
 */
public class DbUtil {
     private static String driver = "com.mysql.cj.jdbc.Driver";
    /*用户名*/
    private static String username = "root";
    /*密码*/
    private static String password = "123456";
    /*数据库名称*/
    private static String database = "xing";
    /*URL格式：jdbc:mysql://IP:端口/数据库名称/？额外参数*/
    private static String url = "jdbc:mysql://localhost:3306/" + database + "?serverTimezone=UTC";

    /**
     * 获取数据库连接
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public Connection getConnection() throws ClassNotFoundException, SQLException {
        /*加载数据库驱动*/
        Class.forName(driver);
        /*获取数据库连接*/
        Connection conn = DriverManager.getConnection(url,username,password);
        if(conn != null){
            System.out.println("数据库连接成功!");
        }else{
            System.out.println("数据库连接失败");
        }
        return conn;
    };
    /**
     * 关闭连接
     * @param conn
     * @throws SQLException
     */
    public void closeConnection(Connection conn) throws SQLException {
        if(conn != null){
            conn.close();
            System.out.println("数据库关闭成功!");
        }else{
            System.out.println("数据库关闭失败");
        }
    }

    /**
     * 关闭语句对象
     * @param statement
     * @throws SQLException
     */
    public void closeStatement(Statement statement) throws SQLException {
        if(statement != null){
            statement.close();
            System.out.println("语句对象关闭成功!");
        }else{
            System.out.println("语句对象关闭失败");
        }
    }

    /**
     * 关闭resultSet
     * @param resultSet
     * @throws SQLException
     */
    public void closeResultSet(ResultSet resultSet) throws SQLException {
        if(resultSet != null){
            resultSet.close();
            System.out.println("resultSet对象关闭成功!");
        }else{
            System.out.println("resultSet对象关闭失败");
        }
    }
}
